﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Configurations.Controller;

namespace Pixysoft.Framework.Configurations.Core
{
    class XmlCommand : IXmlCommand
    {
        string filepath = null;

        string elementName = null;

        XmlConstraintCollection constraints = null;

        public XmlCommand(string filepath)
        {
            this.filepath = filepath;
        }

        public string Filepath
        {
            get
            {
                return filepath;
            }
            set
            {
                filepath = value;
            }
        }

        public string Element
        {
            get
            {
                return elementName;
            }
            set
            {
                if (string.IsNullOrEmpty(value))
                    this.elementName = null;
                else
                    this.elementName = value.Trim().ToUpper();
            }
        }

        public IXmlConstraintCollection Constraints
        {
            get
            {
                return GetConstraints();
            }
        }

        private XmlConstraintCollection GetConstraints()
        {
            if (string.IsNullOrEmpty(elementName))
                throw new Exception("please set elementname first");

            if (constraints == null)
                constraints = new XmlConstraintCollection(elementName);

            return constraints;
        }

        public IXmlTree ExecuteReader()
        {
            //09-12-09 bug must get from property.

            return XmlNodeController.Instance.ExecuteReader(filepath, GetConstraints());
        }

        public List<T> SerializeReader<T>()
        {
            List<T> list = new List<T>();

            IXmlTree tree = ExecuteReader();

            if (tree == null)
                throw new Exception("missing xml tree to serialize.");

            return tree.Serialize<T>();
        }
    }
}
